import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
import '../../models/serach_info_model.dart';
import '../../models/yh_info_model.dart';
import '../../services/yh_info_manger.dart';
import '../../services/number_utils.dart';
import '../../manger/global_config.dart';

class ConfrimYhMaskView extends StatefulWidget {
  final ReListModel? selectedModel;
  final int priceNum;
  final String couponIds;
  final Function(String) onSelectCoupon;
  final VoidCallback onClose;

  const ConfrimYhMaskView({
    Key? key,
    this.selectedModel,
    required this.priceNum,
    required this.couponIds,
    required this.onSelectCoupon,
    required this.onClose,
  }) : super(key: key);

  @override
  _ConfrimYhMaskViewState createState() => _ConfrimYhMaskViewState();
}

class _ConfrimYhMaskViewState extends State<ConfrimYhMaskView> {
  int selectIndex = 0;
  int selectedIndex = -1;

  List<CouponListModel> filteredModels = [];
  List<CouponListModel> unfilteredModels = [];

  @override
  void initState() {
    super.initState();
    updateCouponList();
  }

  void _updateSelectedIndex(String couponIds) {
    int index = filteredModels.indexWhere(
        (coupon) => coupon.spuCouponsId.toString() == couponIds);

    if (index != -1) {
      setState(() {
        selectedIndex = index;
      });
    } else {
      setState(() {
        selectedIndex = -1;
      });
    }
  }

  void updateCouponList() async {
    if (widget.selectedModel == null) return;

    final result = await MyCouponManger().loadDiscountData(
      3,
      spuId: widget.selectedModel?.spuId,
      num: widget.priceNum,
    );
    if (result.success && result.myCoupon != null) {
      setState(() {
        filteredModels = result.myCoupon ?? [];
      });
    }

    final result2 = await MyCouponManger().loadDiscountData(
      4,
      spuId: widget.selectedModel?.spuId,
      num: widget.priceNum,
    );
    if (result2.success && result2.myCoupon != null) {
      setState(() {
        unfilteredModels = result2.myCoupon ?? [];
      });
    }

    _updateSelectedIndex(widget.couponIds);
  }

  void onCouponSelect(int index, CouponListModel model) {
    setState(() {
      selectedIndex = index;
    });
    widget.onSelectCoupon(model.spuCouponsId.toString());
  }

  void onCouponSelectNull() {
    // 不可点击的优惠券
  }

  void onTabSelected(int index) {
    setState(() {
      selectIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    final loc = AppLocalizations.of(context);

    return GestureDetector(
      onTap: () => widget.onClose(),
      child: Container(
        color: Colors.black.withValues(alpha: 0.4),
        child: Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            width: double.infinity,
            height: 560,
            decoration: BoxDecoration(
              color: const Color(0xFFF9F9F9),
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              ),
            ),
            child: Column(
              children: [
                const SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: Center(
                        child: Text(
                          loc?.selectCoupon ?? "Select Coupon",
                          style: const TextStyle(
                              fontSize: 17, fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () => widget.onClose(),
                      child: Container(
                        width: 20,
                        height: 20,
                        margin: const EdgeInsets.only(right: 10),
                        child: const Icon(Icons.close, size: 20),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),
                CouponTopView(
                  onTabSelected: onTabSelected,
                  selectIndex: selectIndex,
                ),
                Expanded(
                  child: Builder(
                    builder: (context) {
                      final list = selectIndex == 0
                          ? filteredModels
                          : unfilteredModels;

                      if (list.isEmpty) {
                        return Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(
                                "assets/images/empty.png",
                                width: 120,
                                height: 120,
                              ),
                              const SizedBox(height: 10),
                              Text(
                                loc!.none + loc.coupon,
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        );
                      }

                      return ListView.builder(
                        itemCount: list.length,
                        itemBuilder: (context, index) {
                          final coupon = list[index];
                          return GestureDetector(
                            onTap: selectIndex == 0
                                ? () => onCouponSelect(index, coupon)
                                : onCouponSelectNull,
                            child: Container(
                              margin: const EdgeInsets.symmetric(
                                  vertical: 0, horizontal: 5),
                              padding: const EdgeInsets.only(
                                  left: 10, right: 10, bottom: 20),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(10),
                                child: Container(
                                  width: double.infinity,
                                  height: 95,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  child: Stack(
                                    children: [
                                      Positioned.fill(
                                        child: Image.asset(
                                          'assets/images/yhj.png',
                                          fit: BoxFit.cover,
                                        ),
                                      ),
                                      if (selectIndex == 1)
                                        Positioned.fill(
                                          child: Container(
                                            color: Colors.white
                                                .withOpacity(0.3),
                                          ),
                                        ),
                                      // 左侧金额
                                      Positioned(
                                        left: 0,
                                        top: 0,
                                        bottom: 0,
                                        width: (MediaQuery.of(context)
                                                    .size
                                                    .width -
                                                30) *
                                            7 /
                                            20,
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            Text(
                                              coupon.type == "1"
                                                  ? "${NumberUtils.formatDecimalValue(coupon.parvalue * 10)}折"
                                                  : '${coupon.symbol ?? ""} ${coupon.parvalue}',
                                              style: const TextStyle(
                                                color: Color(0xFFFF0000),
                                                fontSize: 18,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                            const SizedBox(height: 10),
                                            Text(
                                              "满 ${coupon.symbol ?? ""}${coupon.cill} 可用",
                                              style: const TextStyle(
                                                  fontSize: 12,
                                                  color: Color(0xFFFF0000)),
                                            ),
                                          ],
                                        ),
                                      ),
                                      // 右侧标题
                                      Positioned(
                                        left: (MediaQuery.of(context).size.width -
                                                30) *
                                            8 /
                                            20,
                                        top: 0,
                                        bottom: 0,
                                        width:
                                            (MediaQuery.of(context).size.width -
                                                    30) /
                                                2,
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            Align(
                                              alignment: Alignment.centerLeft,
                                              child: Text(
                                                coupon.name ?? "",
                                                style: const TextStyle(
                                                    fontSize: 14,
                                                    color: Color(0xFF000000)),
                                              ),
                                            ),
                                            const SizedBox(height: 10),
                                            Align(
                                              alignment: Alignment.centerLeft,
                                              child: Text(
                                                coupon.effectiveTime ?? "",
                                                style: const TextStyle(
                                                    fontSize: 12,
                                                    color: Color(0xFF333333)),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      if (selectIndex == 0)
                                        Positioned(
                                          right: 15,
                                          top: 0,
                                          bottom: 0,
                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              Image.asset(
                                                selectedIndex == index
                                                    ? 'assets/images/login_select2.png'
                                                    : 'assets/images/login_unselect2.png',
                                                width: 20,
                                                height: 20,
                                              ),
                                            ],
                                          ),
                                        ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          );
                        },
                      );
                    },
                  ),
                ),
                SizedBox(
                  width: double.infinity,
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 15),
                    child: ElevatedButton(
                      onPressed: () => widget.onClose(),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF5D5FEE),
                        minimumSize: const Size(double.infinity, 40),
                        foregroundColor: Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(18)),
                      ),
                      child: Text(loc?.confirm ?? "Confirm"),
                    ),
                  ),
                ),
                const SizedBox(height: 25),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class CouponTopView extends StatelessWidget {
  final int selectIndex;
  final Function(int) onTabSelected;

  const CouponTopView({
    Key? key,
    required this.onTabSelected,
    required this.selectIndex,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 15, vertical: 0),
      decoration: BoxDecoration(
        color: GlobalConfig.titleBlueColor,
        borderRadius: BorderRadius.circular(17),
      ),
      height: 34,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: List.generate(2, (index) {
          final isSelected = selectIndex == index;
          final title = _getTabTitle(index, context);

          return Expanded(
            child: GestureDetector(
              onTap: () {
                if (selectIndex != index) {
                  onTabSelected(index);
                }
              },
              child: Container(
                margin: const EdgeInsets.all(2),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.white : Colors.transparent,
                  borderRadius: BorderRadius.circular(15),
                ),
                alignment: Alignment.center,
                child: Text(
                  title,
                  style: TextStyle(
                    color:
                        isSelected ? GlobalConfig.titleBlueColor : Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
          );
        }),
      ),
    );
  }

  String _getTabTitle(int index, BuildContext context) {
    final loc = AppLocalizations.of(context);
    switch (index) {
      case 0:
        return loc?.couponDiscounts ?? "Available";
      case 1:
        return loc?.couponDiscountsNo ?? "Unavailable";
      default:
        return '';
    }
  }
}
